<?php

namespace app\api\controller\shop;


use addons\litestore\model\Litestoregoodsspec;
use addons\litestore\model\Wxlitestoregoods;
use app\admin\model\Caiorder;
use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestoreorder;
use app\admin\model\litestore\Litestoreorderaddress;
use app\admin\model\litestore\Litestoreordergoods;
use app\admin\model\litestore\Litestorespecvalue;
use app\admin\model\Litestorecategory;
use app\admin\model\Orderdelivery;
use app\admin\model\Roomclean;
use app\admin\model\Shopmp;
use app\admin\model\Shopstaff;
use app\admin\model\Shopweixin;
use app\admin\model\Tcrule;
use app\admin\model\Useraddress;
use app\admin\model\Userweixin;
use app\api\service\MpService;
use app\api\service\ProfitService;
use app\api\service\TxService;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\model\Area;
use EasyWeChat\Factory;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 *
 */
class Mall extends Api
{
    protected $noNeedLogin = ['sxfOrderCallback'];
    protected $noNeedRight = ['*'];


    public function cateList(){

        $cateModel = new \app\admin\model\litestore\Litestorecategory();
        $list = $cateModel->select();
        $this->success('',$list);
    }




    public function caiGoodsList(){

        $categoryid = $this->request->param('id');
        $page = $this->request->param('page');
        $keyword = $this->request->param('keyword');



        $limit = 200;


        // 筛选条件
        $filter = [];
        $listoreCateModel = new \app\admin\model\litestore\Litestorecategory();


        $pattern = '/^[\p{Han}]+$/u'; // Unicode编码范围匹配中文

            $filter['goods_name'] = array('like','%'.$keyword.'%');


        $filter['goods_status'] = '10';
        $filter['is_delete'] = '0';



        // 排序规则
        $sort = [];

        // 商品表名称
        $model_temp = new Wxlitestoregoods();
        $tableName = $model_temp->getTable();
        // 多规格商品 最高价与最低价
        $GoodsSpec = new Litestoregoodsspec();
        $minPriceSql = $GoodsSpec->field(['MIN(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
        $maxPriceSql = $GoodsSpec->field(['MAX(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();


        $listdata = $model_temp->field(['*', '(sales_initial + sales_actual) as goods_sales',
            "$minPriceSql AS goods_min_price",
            "$maxPriceSql AS goods_max_price"
        ])->with(['spec'])->where($filter)->order($sort)
            ->paginate($limit, false, [ 'page' => $page ]);

        $blistdatarList = [];
        foreach ($listdata as $index => $item) {
            $blistdatarList[] = ['image' => cdnurl(explode(",",$item['images'])[0], true), 'goods_name' => $item['goods_name'],
                'id'=> $item['goods_id'],'goods_min_price'=>$item['goods_min_price'],'goods_max_price'=>$item['goods_max_price'],'goods_sales'=>$item['goods_sales'],'count'=>0];
        }

        $this->success('',$blistdatarList);

    }

    public function detail()
    {
        $goods_id = $this->request->param('goods_id');
        // 商品详情
        $detail = Wxlitestoregoods::detail($goods_id);
        $imgs = [];
        foreach (explode(",", $detail['images']) as $index => $item) {
            $imgs[] = cdnurl($item, true);
        }
        $detail['imgs_url'] = $imgs;

        if (preg_match('/(http:\/\/)|(https:\/\/)/i',  $detail['content'])) {
            $url = "";
        } else {
            $url = "https:";
        }
        $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
        $detail['content'] = preg_replace($pregRule, '<img src="' . $url . '${1}" style="max-width:100%">', $detail['content']);

        $userProfit = 0;
        if (!$detail || $detail['goods_status'] !== '10') {
            $this->error('很抱歉，商品信息不存在或已下架');
        }

        $user = $this->auth->getUser();
        $litestoreGoodSpecModel = new \app\admin\model\litestore\Litestoregoodsspec();
        $spec = $litestoreGoodSpecModel->where('goods_id',$goods_id)->find();
        if($spec){

        }


        // 规格信息
        $specData = $detail['spec_type'] === '20' ? $detail->getManySpecData($detail['spec_rel'], $detail['spec']) : null;

        // 这里对规格的img格式化
        if ($specData != null) {
            foreach ($specData['spec_list'] as $index => $item) {
                $specData['spec_list'][$index]["form"]['imgshow'] = $specData['spec_list'][$index]["form"]['spec_image'] === '' ? null : cdnurl($specData['spec_list'][$index]["form"]['spec_image'], true);
            }
        }




        $this->success('', [
            'detail' => $detail,
            'specData' => $specData,
            'profit' =>round($userProfit,2)
        ]);
    }






    public function addOrder()
    {


        $goods = $this->request->param('goods');
        $pay_type = $this->request->param('pay_type');
        $addressId = $this->request->param('addressId');
        $code = $this->request->param('code');


        $items = json_decode(htmlspecialchars_decode($goods), true);

        $user = $this->auth->getUser();
        $litestoregoodsspec = new Litestoregoodsspec();
        $userAddressModel = new Useraddress();
        $address = $userAddressModel->where('id', $addressId)->find();
        if (!$address) {
            $this->error('请添加收货地址');
        }
        $totalAmount = 0;
        $totalCount = 0;
        $str = "";
        $profit = 0;

        $expressAmount = 0;
        $payAmount = 0;
        $is_vip = -1;
        $listoreGoodModel = new Litestoregoods();

        $expressAmount = 0;


        $userWxModel = new Shopweixin();
        $wx = $userWxModel->where('user_id', $user['id'])->find();
        if(!$wx){
            $config = [
                'app_id' => "wx1ff50178a92f6e7d",
                'secret' => "4f68cf38af57e01a60d5bb3919653ae0",
                'response_type' => 'array',
                'log' => [
                    'level' => 'debug',
                ],
            ];
            $this->app = Factory::miniProgram($config);

            $ret = $this->app->auth->session($code);
            if (isset($ret["errcode"]) && $ret['errcode'] == '40163') {
                $this->error('请重新获取code');
            } else {
                $openid = $ret['openid'];
                $session_key = $ret['session_key'];
                $userwx = $userWxModel->where('user_id', $user['id'])->find();
                if($userwx){
                    $userWxModel->where('id',$userwx['id'])->update(['openid'=>$openid]);
                }else{
                    $userWxModel->insert(['openid'=>$openid,'user_id'=>$user['id']]);
                }

            }
        }

        foreach ($items as $key => $val) {
            $good = $litestoregoodsspec->where('goods_id', $val['goods_id'])->where('spec_sku_id', $val['skuId'])->find();
            if ($key <= 2) {
                $str .= $val['goods_name'] . ",";
            }
            $goods = $listoreGoodModel->where('goods_id', $val['goods_id'])->find();


            error_log("===good===" . json_encode($good));
            $totalPrice = bcmul($good['goods_price'], $val['count'], 2);
            $items[$key]['totalPrice'] = $totalPrice;
            $items[$key]['price'] = $good['goods_price'];
            $items[$key]['goods_spec_id'] = $good['goods_spec_id'];

            $totalCount += $val['count'];
            $totalAmount = $totalAmount + $totalPrice;
        }


        $data = array();


        $orderNo = getOrderSn();

        $totalAmount = round($totalAmount + $expressAmount, 2);

        $data['orderNo'] = $orderNo;
        $data['amount'] = $totalAmount;
        $data['address'] = $address;
        $data['goods'] = $items;
        $data['count'] = $totalCount;
        $data['express_amount'] = $expressAmount;
        $data['pay_type'] = $pay_type;

        $pay = round($data['amount'], 2);
        $data['pay_amount'] = $pay;
        $liteorder = new Litestoreorder();
        $orderId = $liteorder->addOrder($user['id'], $data);

        if ($orderId) {
            $info = array();
            $info['orderNo'] = $orderNo;
            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/shop/mall/sxfOrderCallback";

            $req['mno'] = "399230630431837";
            $req['ordNo'] = $orderNo;
            $req['amt'] = $pay;




            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = "wx1ff50178a92f6e7d";
            $req['userId'] = $wx['openid'];

            $req['subject'] = "产品购买";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;

            


            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);

            error_log("--=====pay===".json_encode($res));
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $orderNo;
                $info['payInfo'] = $result['respData'];

                $this->success('', $info);
            } else {
                $this->error($bizMsg);
            }

            $this->success('下单成功', $info);
        } else {
            $this->error("下单失败，请联系客服");
        }

    }


    public function sxfOrderCallback()
    {

        $param = file_get_contents("php://input");

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);
            $listoreModel = new Litestoreorder();
            $litestoreGoodModel = new Litestoreordergoods();
            $order = $listoreModel->where('order_no', $out_trade_no)->find();
            $listoreModel->where('order_no', $out_trade_no)->update(['pay_status' => '20', 'pay_time' => time()]);

            $litestoreGoodModel->where('order_id',$order['id'])->update(['status'=>'payed']);

            $msgKey = "msg_order_" . $order['id'];
            $isCount = $this->redis->get($msgKey);
            if (!$isCount) {
                $this->redis->set($msgKey, 1, 24 * 60 * 60);
            }






        }

    }

    public function orderDetail()
    {

        $orderNo = $this->request->param('orderNo');
        $liteOrderModel = new Litestoreorder();
        $order = $liteOrderModel->where('order_no', $orderNo)->find();
        $liteorderGoods = new Litestoreordergoods();
        $orderGood = $liteorderGoods->where('order_id', $order['id'])->select();
        $specGoodModel = new \app\admin\model\litestore\Litestoregoodsspec();
        $specValueModel =new Litestorespecvalue();
        foreach ($orderGood as $key => $val) {

            $spec = $specGoodModel->where('goods_spec_id',$val['goods_spec_id'])->find();
            $value = $specValueModel->where('id',$spec['spec_sku_id'])->find();
            if($value){
                $orderGood[$key]['spec_name'] =$value['spec_value'];
            }else{
                $orderGood[$key]['spec_name'] = "";
            }
            $orderGood[$key]['image'] = cdnurl(explode(",", $val['images'])[0], true);
        }
        $areaModel = new Area();
        $orderAddressModel = new Litestoreorderaddress();
        $address = $orderAddressModel->where('order_id', $order['id'])->find();

        $provice = $areaModel->where('id', $address['province_id'])->find();
        $city = $areaModel->where('id', $address['city_id'])->find();
        $region = $areaModel->where('id', $address['region_id'])->find();

        $address['province'] = $provice['name'];
        $address['city'] = $city['name'];
        $address['areaStr'] = $region['name'];


        $data = array();
        $data['goods'] = $orderGood;
        $data['address'] = $address;

        if ($order['pay_status'] == '10' && $order['order_status'] == '10') {
            $order['status'] = '待支付';
        } else if ($order['pay_status'] == '20' && $order['freight_status'] == '10'  && $order['order_status'] == '10') {
            $order['status'] = '待发货';
        } else if ($order['pay_status'] == '20' && $order['receipt_status'] == '10' && $order['order_status'] == '10') {
            $order['status'] = '待收货';
        } else if ($order['order_status'] == '30') {
            $order['status'] = '已完成';
        } else if ($order['order_status'] == '20' && $order['pay_status'] == '20') {
            $order['status'] = '已退款';
        }else{
            $order['status'] = '已取消';

        }
        $order['createtime'] = date("Y-m-d H:i:s", $order['createtime']);
        $data['order'] = $order;

        $this->success('', $data);
    }


    public function orderList()
    {

        $user = $this->auth->getUser();

        $page = $this->request->param('page');
        $status = $this->request->param('status');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        error_log("==user===" . json_encode($user));
        $where = [];
        $where['user_id'] = $user['id'];
        if ($status == 'payed') {
            $where['pay_status'] = '20';
            $where['freight_status'] = '10';
            $where['order_status'] = '10';

        } else if ($status == 'transit') {
            $where['pay_status'] = '20';
            $where['freight_status'] = '20';
            $where['order_status'] = '10';
        } else if ($status == 'done') {
            $where['order_status'] = '30';
        } else if ($status == 'paying') {
            $where['pay_status'] = '10';
            $where['order_status'] = '10';
        }

        $litestoreorder = new Litestoreorder();
        $list = $litestoreorder->with(['goods'])
            ->where($where)
            ->order(['createtime' => 'desc'])->limit($offset, $limit)
            ->select();

        $newList = [];
        $goodSpecModel = new \app\admin\model\litestore\Litestoregoodsspec();
        foreach ($list as $key => $val) {

            if ($val['pay_status'] == '10' && $val['order_status'] == '10') {
                $list[$key]['status'] = '待支付';
            } else if ($val['pay_status'] == '20' && $val['freight_status'] == '10') {
                $list[$key]['status'] = '待发货';
            } else if ($val['pay_status'] == '20' && $val['receipt_status'] == '10') {
                $list[$key]['status'] = '待收货';
            } else if ($val['order_status'] == '30') {
                $list[$key]['status'] = '已完成';
            } else if ($val['order_status'] == '20') {
                $list[$key]['status'] = '已取消';
            }
            $obj = [];
            $obj['status'] = $val['status'];
            $obj['orderNo'] = $val['order_no'];
            $obj['total_price'] = $val['total_price'];
            $obj['total_price'] = $val['total_price'];

            $obj['createtime'] = date("Y-m-d H:i:s", $val['createtime']);
            $goods = $val['goods'];
            $good = array();
            $totalCount = 0;
            foreach ($goods as $k => $v) {
                $goodObj = array();
                $goodObj['good_name'] = $v['goods_name'];
                $goodObj['goods_price'] = $v['goods_price'];
                $goodObj['total_num'] = $v['total_num'];

                $goodObj['image'] = cdnurl(explode(",", $v['images'])[0], true);
                $good[] = $goodObj;
                $totalCount += $v['total_num'];
            }
            $obj['totalCount'] = $totalCount;
            $obj['goods'] = $good;
            $newList[] = $obj;

        }

        $this->success('', $newList);


    }


    public function cancel(){

        $order_no = $this->request->param('order_no');
        $litestoreOrderModel = new Litestoreorder();
        $order = $litestoreOrderModel->where('order_no',$order_no)->find();
        if($order['pay_status'] == 10){
            $litestoreOrderModel->where('id',$order['id'])->update(['order_status'=>20]);
        }

        $this->success("成功");
    }



    public function pay(){

        $order_no = $this->request->param('order_no');
        $litestoreOrderModel = new Litestoreorder();
        $order = $litestoreOrderModel->where('order_no',$order_no)->find();

        if ($order['pay_status'] == 10) {

            $newOrderNo = getOrderSn();
            $litestoreOrderModel->where('id',$order['id'])->update(['order_no'=>$newOrderNo]);
            $info = array();
            $info['orderNo'] = $newOrderNo;
            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/shop/mall/sxfOrderCallback";

            $req['mno'] = "399230630431837";
            $req['ordNo'] = $newOrderNo;
            $req['amt'] = $order['pay_price'];


            $userWxModel = new Shopweixin();
            $wx = $userWxModel->where('user_id', $order['user_id'])->find();

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = "wx1ff50178a92f6e7d";
            $req['userId'] = $wx['openid'];

            $req['subject'] = "产品购买";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;


            error_log("===req==".json_encode($req));
            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);

            error_log("--=====pay===".json_encode($res));
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $newOrderNo;
                $info['payInfo'] = $result['respData'];

                $this->success('', $info);
            } else {
                $this->error($bizMsg);
            }

            $this->success('下单成功', $info);
        } else {
            $this->error("下单失败，请联系客服");
        }

    }


}
